from tkinter import *
import time
#from KataGoHelper import KataGo, Color, Move
from KataGoGtpHelper import KataGoGtp
from board import BoardFrame
from YeHuUiHelper import YeHuUiHelper
import threading
import numpy as np
'''
运行过程：
1、初始化
2、点一步走一步
'''
class Myapp(Frame):
    def __init__(self, master):
        super().__init__()
        eg = 'bs'
        self.katago = KataGoGtp('D:\\katago'+eg+'\\katago.exe', 'D:\\katago'+eg+'\\g.cfg', 'D:\\katago'+eg+'\\model.bin.gz')
        while not self.katago.ok:
            time.sleep(1)
        self.boardArrRec=np.zeros((19, 19), dtype=np.int8)
        self.yehuHelper = YeHuUiHelper()
        self.master = master
        self.pack()
        self.createWidget()
        self.master.protocol("WM_DELETE_WINDOW", self.exit_sys)


    def exit_sys(self):
        print('exit sys')
        self.katago.close()
        self.master.destroy()

    def setStauts(self, str):
        self.status.set(str)
    

    def bt_init_click(self):
        self.yehuHelper.FindMainBoard()
        #self.yehuHelper.FindRecBoard()
        if self.yehuHelper.YeHuWindowsInitOk():
            self.yehuHelper.SetYeHuWindowPos()
            self.setStauts('成功初始化')
        else:
            self.setStauts('未找到下棋窗口')

    def bt_init_dp_click(self):
        self.yehuHelper.FindRecBoard()
        if self.yehuHelper.YeHuWindowsInitOk():
            self.yehuHelper.SetYeHuWindowPos()
            self.setStauts('成功初始化')
        else:
            self.setStauts('未找到下棋窗口')


    def read_board(self):
        found = False
        #self.board.reset()
        board=self.yehuHelper.Recognition()
        for y in range(19):
            for x in range(19):
                color = board[y][x] # + w b
                if color!=0 and self.boardArrRec[y][x]==0:
                    _c='w' if color==1 else 'b'
                    self.katago.play_pos(_c, x, y)
                    found=True
        if found:
            self.board.setBoard(board)
            self.boardArrRec=board
        return found

    def play(self, _c):
        res = self.katago.genmove(_c)
        self.boardArrRec[res[1]][res[0]]=1 if _c=='w' else 2
        #self.katago.showboard()
        self.board.play(res[1], res[0], _c, False)
        self.yehuHelper.MouseClick(res[0], res[1])
        self.setStauts(_c+' '+str(res))


    def bt_w_click(self):
        self.read_board()
        self.play('w')
        self.katago.showboard()


    def bt_b_click(self):
        self.read_board()
        self.play('b')
        self.katago.showboard()


    def bt_auto_w_click(self):
        self.auto_run = True
        self.auto_th = threading.Thread(target=Myapp.__auto_play, args=(self, 'w',))
        self.auto_th.start()

    def bt_auto_b_click(self):
        self.auto_run = True
        self.auto_th = threading.Thread(target=Myapp.__auto_play, args=(self, 'b',))
        self.auto_th.start()

    def __auto_play(self, color: str):
        if color=='b':
            b_init = True
        while self.auto_run:
            if self.read_board() or b_init:
                b_init=False
                self.play(color)
            time.sleep(1)

    def bt_stop_auto_click(self):
        self.auto_run = False

    def bt_clear_board_click(self):
        self.katago.clear_board()
        self.board.reset()

    def gtp_showboard(self):
        self.katago.showboard()

    def createWidget(self):
        self.status = StringVar()
        self.stauts_bar = Label(self.master,
                                text='状态',
                                textvariable=self.status,
                                relief=SUNKEN,
                                anchor=W)
        self.stauts_bar.pack(side=BOTTOM,fill=X)
        self.status.set('信息')

        self.button_frame=Frame(self.master, relief=SUNKEN, width=120)

        Button(self.button_frame, text='初始化下棋', command=self.bt_init_click).pack(pady=(8,0), anchor=W, fill=X)
        Button(self.button_frame, text='初始化打谱', command=self.bt_init_dp_click).pack(pady=(8,0), anchor=W, fill=X)
        Button(self.button_frame, text='走白棋', command=self.bt_w_click).pack(pady=(8,0), anchor=W, fill=X)
        Button(self.button_frame, text='走黑棋', command=self.bt_b_click).pack(pady=(8,0), anchor=W, fill=X)
        Button(self.button_frame, text='自动走白棋', command=self.bt_auto_w_click).pack(pady=(8,0), anchor=W, fill=X)
        Button(self.button_frame, text='自动走黑棋', command=self.bt_auto_b_click).pack(pady=(8,0), anchor=W, fill=X)
        Button(self.button_frame, text='停止自动走棋', command=self.bt_stop_auto_click).pack(pady=(8,0), anchor=W, fill=X)
        Button(self.button_frame, text='清空棋盘', command=self.bt_clear_board_click).pack(pady=(8,0), anchor=W, fill=X)
        Button(self.button_frame, text='读棋盘', command=self.read_board).pack(pady=(8,0), anchor=W, fill=X)
        Button(self.button_frame, text='打印GTP', command=self.gtp_showboard).pack(pady=(8,0), anchor=W, fill=X)
        
        
        self.button_frame.pack(side=LEFT,fill=Y,padx=(8,8))
        self.button_frame.pack_propagate(0)

        self.board = BoardFrame(self.master)
        self.board._frame.pack(side=RIGHT, pady=16, padx=16)


if __name__ == '__main__':
    root = Tk()
    root.title('习题采集')
    root.geometry('620x500')
    app = Myapp(master=root)
    app.mainloop()